<template>
    <el-row>
        <el-col :span="24">
            <h1 style="display: inline-block;padding-right: 700px;">我的商品</h1>
            <el-button style="display: inline-block;" type="primary" @click="dialogVisible=true">新增商品</el-button>
        </el-col>
    </el-row>

    <el-row :gutter="20">

        <el-col :span="21" :offset="0">            
            <el-table :data="productList">
                <el-table-column prop="name" label="商品名称" width="200px"></el-table-column>
                <el-table-column prop="number" label="商品库存" width="200px"></el-table-column>
                <el-table-column prop="price" label="商品价格" width="200px">
                    <template #default="scope">
                        {{ scope.row.price }} 元
                    </template>
                </el-table-column>
                <el-table-column prop="caozuo" label="操作" width="237px">
                    <template #default="scope">
                        <el-button type="primary" @click="editProduct(scope.row.id)">编辑</el-button>
                        <el-button type="danger" @click="deleteProduct(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog :title="dialogtitle" v-model="dialogVisible" :before-close="handleClose">
                <el-form>
                    <el-form-item label="商品名称">
                        <el-input placeholder="请输入商品名称" v-model="formData.name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品描述">
                        <el-input placeholder="请输入商品描述" v-model="formData.description"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格">
                        <el-input placeholder="请输入商品价格" v-model="formData.price"></el-input>
                   </el-form-item>
                    <el-form-item label="商品库存">
                        <el-input placeholder="请输入商品库存" v-model="formData.number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类">
                        <el-select v-model="formData.category">
                            <el-option label="蔬菜" value="蔬菜"></el-option>
                            <el-option label="水果" value="水果"></el-option>
                            <el-option label="豆类" value="豆类"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品状态">
                        <el-select v-model="formData.status">
                            <el-option label="上架" value="1"></el-option>
                            <el-option label="下架" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品图片" v-show="formData.id">
                        <img :src="BASE_URL+formData.imageUrl" style="width: 100px;" alt="">
                    </el-form-item>
                    <el-form-item label="商品图片" v-show="!formData.id">
                        <el-upload
                                v-model:file-list="fileList"
                                v-model:action="actionUrl"
                                name="file"
                                limit="1"
                                list-type="picture-card"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                                >
                                <el-icon>
                                    <Plus/>
                                </el-icon>
                                </el-upload>
                                <el-dialog v-model="dialogImgVisible">
                                    <el-image w-full :fit="contain"  :src="dialogImageUrl"/>
                                </el-dialog>
                    </el-form-item>
                    <el-form-item style="margin: 0 auto;width: 200px;">
                        <el-button v-show="!formData.id" type="primary" @click="addproduct">确认</el-button>
                        <el-button v-show="formData.id" type="primary" @click="saveproduct">保存</el-button>
                        <el-button @click="handleClose">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-col>
        <el-col :span="3" :offset="0"></el-col>
    </el-row>
    

</template>


<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage} from 'element-plus'
import axios from 'axios'
import qs from 'qs'

const user =ref(JSON.parse(localStorage.getItem('user'))) 
/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogImgVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL+'/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
      .then((response)=>{
        if (response.data.code==2000){
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogImgVisible.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}

/**图片上传相关代码结束**/

//定义新增商品弹窗的变量
const dialogVisible = ref(false)
//定义新增商品的表单数据
const formData = ref({
    id:'',
    name:'',
    description:'',
    price:'',
    number:'',
    category:'',
    status:'',
    imageUrl:'',
    sellerId:''
})
//定义数组保存商品列表数据
const productList = ref([])
//获取商品列表数据
const getProductList = () => {
    let id = user.value.id
    axios.get(BASE_URL+'/v1/product/list?sellerId='+id+'&&status=-1').then(res=>{
        if (res.data.code === 2000) {
            productList.value = res.data.data
        } else {
            ElMessage.error(res.data.msg);
        }
    })
}

onMounted(() => {
    getProductList()
})

//定义添加新商品功能
const addproduct = () => {

    if (!formData.value.name) {
        ElMessage.error('请输入商品名称!');
        return;
    }
    if (!formData.value.description) {
        ElMessage.error('请输入商品描述!');
        return;
    }
    if (!formData.value.price) {
        ElMessage.error('请输入商品价格!');
        return;
    }
    if (!formData.value.number) {
        ElMessage.error('请输入商品库存!');
        return;
    }
    if (!formData.value.category) {
        ElMessage.error('请选择商品类别!');
        return;
    }
    if (!formData.value.status) {
        ElMessage.error('请选择商品状态!');
        return;
    }
    if (!fileList.value[0]) {
        ElMessage.error('请上传商品图片!');
        return;
    }
    console.log(formData.value)
    formData.value.imageUrl = fileList.value[0].response.data
    formData.value.sellerId = user.value.id
    console.log(user.value)
    console.log(formData.value)

    let data = qs.stringify(formData.value)
    axios.post(BASE_URL+'/v1/product/add',data).then(res=>{
        if (res.data.code === 2000) {
            ElMessage.success('新增商品成功!');
            dialogVisible.value = false;
            formData.value = {}
                //清空上传的图片
            fileList.value = []
            getProductList()
        } else {
            ElMessage.error(res.data.msg);
        }
    })
}
// 定义弹窗标题
const dialogtitle = ref('新增商品')
//定义编辑功能
const editProduct = (id) => {
    formData.value.id = id
    dialogVisible.value = true
    dialogtitle.value = '编辑商品'
    axios.get(BASE_URL+'/v1/product/select/'+id).then(response => {
        if (response.data.code === 2000) {
            formData.value = response.data.data
            
        } else {
            ElMessage.error(response.data.msg)
        }
    })
}
//定义关闭弹窗
const handleClose = () => {
    dialogVisible.value = false
    formData.value = {
    }
    //清空上传的图片
    fileList.value = []
}

//定义删除功能
const deleteProduct = (id) => {
    axios.post(BASE_URL+'/v1/product/delete/'+id).then(response => {
        if (response.data.code === 2000) {
            ElMessage.success('删除成功!');
            getProductList()
        } else {
            ElMessage.error(response.data.msg)
        }
    })
}

//定义保存商品功能
const saveproduct = () => {
    let data = qs.stringify(formData.value)
    axios.post(BASE_URL+'/v1/product/update',data).then(response => {
    if (response.data.code === 2000) {
        ElMessage.success('修改商品成功!');
        dialogVisible.value = false;
        formData.value = {}
        getProductList()
        //清空上传的图片
        fileList.value = []
        }
    })
}

</script>

<style scoped>

</style>